<template>
	<div class="box11">
		<el-row>
			<el-col :span="22" :offset="1">
				<div class="header_add">
					<h2 class="add" v-if="flag2">添加</h2>
					<h2 class="add" v-if="flag1">修改</h2>
					<el-button type="primary" size="default" @click="backindex">返回</el-button>
				</div>
			
				<div class="tabfrom">
					<el-form :model="ruleForm" :hide-required-asterisk='true' :rules="rules" ref="ruleForm"
						label-width="100px" class="demo-ruleForm">
						<el-form-item class="imageaa" label="商品封面">
							<el-upload ref="upload"
								class="avatar-uploader" 
								:action="basurl + 'ware/uploadCover'"
								:show-file-list="false" 
								:on-success="handleCoverSuccess"
								:before-upload="beforeAvatarUpload">
								<img v-if="imgUrl" :src="imgUrl" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
						<label class="tuTitle">上传图片：</label>
						<div class="myImg">
							
							<el-form-item prop="files">
								<el-upload 
									ref="upload"
								    action=""
									:auto-upload="false" 
									:file-list="wareImgList"
									:on-change="handleChange1"
									:before-upload="beforeAvatarUpload"
									list-type="picture-card" 
									:on-remove="handleRemove1">
									<i class="el-icon-plus  avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</div>
						<label class="tuTitle">详情图片：</label>
						<div class="myImg">
							
							<el-form-item prop="files">
								<el-upload 
									ref="upload"
								    action=""
									:auto-upload="false" 
									:file-list="wareDetailsList"
									:on-change="handleChange2"
									:before-upload="beforeAvatarUpload"
									list-type="picture-card" 
									:on-remove="handleRemove2">
									<i class="el-icon-plus  avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</div>
						<el-form-item label="商品名称：" prop="wareName">
							<el-input placeholder="请填写商品名称" v-model="ruleForm.wareName"></el-input>
						</el-form-item>
						<el-form-item label="库存量：" prop="num">
							<el-input placeholder="请填写商品库存量" v-model="ruleForm.num"></el-input>
						</el-form-item>
						<el-form-item label="商品原价：" prop="price">
							<el-input placeholder="请填写商品原价" v-model="ruleForm.price"></el-input>
						</el-form-item>
						<el-form-item label="会员价：" prop="vipPrice">
							<el-input placeholder="请填写商品会员价" v-model="ruleForm.vipPrice"></el-input>
						</el-form-item>
						<el-form-item label="商品香型：" prop="flavor">
							<el-select v-model="ruleForm.flavor" placeholder="请选择商品香型">
								<el-option v-for="flaovr in flavorlist" :label="flaovr.classifyName"
									:key="flaovr.classifyId" :value="flaovr.classifyId"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="商品类别：" prop="type">
							<!-- 	<el-input placeholder="请填写类别" v-model="ruleForm.type"></el-input> -->
							<el-select v-model="ruleForm.type" placeholder="请选择商品类别">
								<!-- <el-option label="普通商品" value=0></el-option>
								<el-option label="积分商品" value=1></el-option> -->
								<el-option v-for="lei in leiixng" :label="lei.name" :value="lei.id"
									:key="lei.id"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="商品度数：" prop="proof">
							<!-- <el-input placeholder="请填写商品度数" v-model="ruleForm.proof"></el-input> -->
							<el-select v-model="ruleForm.proof" placeholder="请选择商品度数">
								<el-option v-for="proof in prooflist" :label="proof.classifyName" :value="proof.classifyId"
									:key="proof.classifyId"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="商品品牌：" prop="brand">
							<!-- 	<el-input placeholder="请填写商品品牌" v-model="ruleForm.brand"></el-input> -->
							<el-select v-model="ruleForm.brand" placeholder="请选择商品品牌">
								<el-option v-for="brand in brandlist" :label="brand.classifyName" :value="brand.classifyId"
									:key="brand.classifyId"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="商品备注：" prop="wareDescr">
							<el-input placeholder="请填写商品备注" v-model="ruleForm.wareDescr"></el-input>
						</el-form-item>
						
						<el-form-item v-if="newwareId" label="上架操作：" prop="downStatus">
							<el-select v-model="downStatus">
								<el-option label="上架" value="1"></el-option>
								<el-option label="下架" value="0"></el-option>
							</el-select>
						</el-form-item>
						<!-- <el-form-item label="商品详情：" prop="wareDetails">
							<el-input type="textarea" v-model="ruleForm.wareDetails"></el-input>
						</el-form-item> -->
						<el-form-item class="btnadd">
							<el-button v-if="flag2" type="primary" @click="addtquedng('ruleForm')">添加</el-button>
							<el-button v-if="flag2" @click="resetForm('ruleForm')">重置</el-button>
							<el-button v-if="flag1" type="primary" @click="xuigaigoods('ruleForm')">修改</el-button>
							<el-button v-if="flag1" @click="nogoods('ruleForm')">取消</el-button>

						</el-form-item>
					</el-form>
					
				</div>
			</el-col>
		</el-row>
	</div>
</template>
<script>
	import axios from "axios";
export default {
	data() {
		var numku = (rule, value, callback) => {
			var reg = /^[0-9]*$/
			if (value === '') {
				callback(new Error('请输入库存量'));
			} else if (!reg.test(value)) {
				callback(new Error('只能填数字'));
			} else {
				callback();
			}
		}
		var numka = (rule, value, callback) => {
			var reg = /^[0-9]+\.{0,1}[0-9]{0,2}$/
			if (value === '') {
				callback(new Error('请输入价格'));
			} else if (!reg.test(value)) {
				callback(new Error('只能填数字'));
			} else {
				callback();
			}
		}
		var numkv = (rule, value, callback) => {
			var reg = /^[0-9]+\.{0,1}[0-9]{0,2}$/
			if (value === '') {
				callback(new Error('请输入库vip价格'));
			} else if (!reg.test(value)) {
				callback(new Error('只能填数字'));
			} else {
				callback();
			}
		}

		return {
			
			newwareId: "",//修改需要的id
			basurl: require('../assets/baseUrl').baseUrl,
			imgUrl: "",//require('../assets/add.jpg')
			filed: {},
			flag1: true,
			flag2: true,
			leiixng: [{ id: 0, name: "普通商品" }, { id: 1, name: "积分商品" }],
			ruleForm: {
				wareName: '', //商品名称，String 1
				wareImg: '',//商品图片名称，String 1
				wareDetails: '',//商品详情，String 1
				wareDescr: '', //商品备注，String 1
				brand: "", //品牌ID,int 1
				flavor: '',//香型ID，int
				proof: "", //度数ID，int 1
				num: "",  //库存，int 1
				price: "",//原价，Bigdecmail 1
				vipPrice: "",//vipPrice，Bigdecmail 1
				type: "", //商品类型，int 1
			},
			goodsnew: {

			},//修改前的数据
			imagearurl: '',//
			rules: {
				wareName: [
					{ required: true, message: '请输入商品名称', trigger: 'change' },
				],
				wareDetails: [
					{ required: true, message: '请输入商品详情', trigger: 'change' }
				],
				wareDescr: [
					{ required: true, message: '请输入商品备注', trigger: 'change' }
				],
				brand: [
					{ required: true, message: '请选择品牌', trigger: 'change' }
				],
				flavor: [
					{ required: true, message: '请选择香型', trigger: 'change' }
				],
				proof: [
					{ required: true, message: '请选择度数', trigger: 'change' }
				],
				num: [
					{ validator: numku, trigger: 'change' }
				],
				price: [
					{ validator: numka, trigger: 'change' }
				],
				vipPrice: [
					{ validator: numkv, trigger: 'change' }
				],
				type: [
					{ required: true, message: '请选择度数', trigger: 'change' }
				],
			},
			brandlist: '',//所有品牌
			flavorlist: "",//所有香型
			prooflist: "",//所有度数
			coverImg:"",//封面
			fileList1:[],
			fileList2:[],
			imgAll:"",
			detailImgAll:"",
			wareImgList:[],
			wareDetailsList:[],
			wareImg:"",
			wareDetails:"",
			downStatus:"",
		};
	},
	methods: {
		handleRemove1(file, fileList) {
			
			if(this.wareImg){
				var imgArr=this.wareImg.split(',');
				var result=[]
				fileList.forEach(v=>{
					result.push(v.name)
				})
				var s=new Set(result);
				var mm=imgArr.filter(v=>s.has(v))
				this.wareImg=mm.join(",")
			}
			
			this.fileList1=fileList
		},
		handleChange1(file, fileList){
			//this.fileList.push(file.raw);
			this.fileList1=fileList
		},
		handleRemove2(file, fileList) {
			if(this.wareDetails){
				var imgArr=this.wareDetails.split(',');
				var result=[]
				fileList.forEach(v=>{
					result.push(v.name)
				})
				var s=new Set(result);
				var mm=imgArr.filter(v=>s.has(v))
				this.wareDetails=mm.join(",")
			}
			this.fileList2=fileList
		},
		handleChange2(file, fileList){
			//this.fileList.push(file.raw);
			this.fileList2=fileList
		},
		handleCoverSuccess(res, file) {
			this.ruleForm.wareImg = file.response.msg
			this.imgUrl = URL.createObjectURL(file.raw);
			//console.log("封面上传成功",res.msg)
			this.coverImg=res.msg
		},
		//取消
		nogoods() {
			/* this.$router.push("/projectmananger/projectlist") */
			this.ruleForm = { ...this.goodsnew }
			this.imgUrl = this.imagearurl


		},
		//修改
		xuigaigoods(Formrule) {
			//console.log("修改")
			this.$refs[Formrule].validate((valid) => {
				if (valid) {
					//console.log("修改",this.fileList1)
					if(this.fileList1.length!=0){
						this.uploadImgAll()
					}else if(this.fileList2.length!=0){
						this.uploaDetailImgAll()
					}else{
						
						this.updateGoodsFn()
					}
				}
			})
		},
		//返回
		backindex() {
			this.$router.push("/projectmananger/projectlist")
		},
		//限制图片大小个图片类型
		beforeAvatarUpload(file) {
			const isJPG = file.type === 'image/jpeg';
			const isLt2M = file.size / 1024 / 1024 < 2;

			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isJPG && isLt2M;
		},
		//点击确认添加
		addtquedng(Formrule) {
			/* if(this.imgUrl!=""){
				this.addgoods(Formrule)
			}else{
				this.addgoods(Formrule)
				this.$message.error('请添加图片');
					
			} */
			this.addgoods(Formrule)



		},
		
		//批量上传商品图片
		uploadImgAll(){
			var formData=new FormData();
			this.fileList1.forEach(x => {
				if(x.raw){
					formData.append("files",x.raw);
				}
			})
			if(!formData.get('files')){
				//不上传，直接修改
				this.updateGoodsFn();
				return;
			}
			
			this.$http.post(this.basurl + "ware/uploadImg", formData).then(res=>{
				//console.log(res)
				if(res.data.code==200){
					this.imgAll=res.data.data.join(',')
					
					if(!this.newwareId){
						if(this.fileList2.length==0){
							this.$message.error('未添加详情图片');
							return
						}
					}else{
						//console.log('imgAll',this.wareImg+','+this.imgAll)
						this.wareImg=this.wareImg+','+this.imgAll
						if(this.fileList2.length==0){
							this.updateGoodsFn();
							return
						}
					}
					this.uploaDetailImgAll()
				}else{
					this.$message.error(res.data.msg)
				}
			})
		},
		uploaDetailImgAll(){
			var formData=new FormData();
			this.fileList2.forEach(x => {
				if(x.raw){
					formData.append("files",x.raw);
				}
			})
			if(!formData.get('files')){
				//不上传，直接修改
				this.updateGoodsFn();
				return;
			}
			this.$http.post(this.basurl + "ware/uploadDetails", formData).then(res=>{
				
				if(res.data.code==200){
					this.detailImgAll=res.data.data.join(',')
					if(!this.newwareId){//添加
						var data={
								"wareName": this.ruleForm.wareName,      //商品名称，String
								"wareCover": this.coverImg,        //商品封面，String
								"wareImg":this.imgAll,//商品图片
								"wareDetails": this.detailImgAll,   //商品详情，String
								"wareDescr": this.ruleForm.wareDescr,     //商品备注，String
								"brand": this.ruleForm.brand,                 //品牌ID,int
								"flavor": this.ruleForm.flavor,             //香型ID，int
								"proof": this.ruleForm.proof,             //度数ID，int
								"num": this.ruleForm.num,               //库存，ID
								"price": this.ruleForm.price,             //原价，Bigdecmail
								"vipPrice": this.ruleForm.vipPrice,           //vipPrice，Bigdecmail
								"type": this.ruleForm.type,
								
						}
						this.addGoodsFn(data);
					}else{//修改
						this.wareDetails=this.detailImgAll+','+this.wareDetails
						
						this.updateGoodsFn();
					}
					
				}else{
					this.$message.error(res.data.msg)
				}
			})
		},
		updateGoodsFn(){
			
			var data={
					"wareName": this.ruleForm.wareName,      //商品名称，String
					"wareCover": this.coverImg,        //商品封面，String
					"wareImg":this.wareImg,//商品图片
					"wareDetails": this.wareDetails,   //商品详情，String
					"wareDescr": this.ruleForm.wareDescr,     //商品备注，String
					"brand": this.ruleForm.brand,                 //品牌ID,int
					"flavor": this.ruleForm.flavor,             //香型ID，int
					"proof": this.ruleForm.proof,             //度数ID，int
					"num": this.ruleForm.num,               //库存，ID
					"price": this.ruleForm.price,             //原价，Bigdecmail
					"vipPrice": this.ruleForm.vipPrice,           //vipPrice，Bigdecmail
					"type": this.ruleForm.type,
					"wareId": this.newwareId,
					downStatus:this.downStatus
			}
			//console.log('data',data)
			this.$http.post(this.basurl + "ware/updateWare",data).then(res => {
				
				if (res.data.code == 200) {
					this.$message.success('修改成功');
					
					this.$router.push('/projectmananger/projectlist')
				} else {
					this.$message.error(res.data.msg)
				}
			})
		},
		addGoodsFn(data){
			this.$http.post(this.basurl + "ware/insertWare",data).then(res => {
				/* console.log(res) */
				if (res.data.code == 200) {
					this.$message.success('添加成功');
					//this.resetForm('ruleForm')
					this.$router.push('/projectmananger/projectlist')
				} else {
					this.$message.error(res.data.msg)
				}
			})
		},
		//添加接口
		addgoods(Formrule) {
			this.$refs[Formrule].validate((valid) => {
				
				if (valid) {
					if(this.imgUrl==""){
						this.$message.error('未添加封面');
					}else if(this.fileList1.length==0){
						this.$message.error('未添加商品图片');
						return
					}
					this.uploadImgAll()
				}
			})

		},
		//重置
		resetForm(ruleForm) {
			this.$refs[ruleForm].resetFields();
			this.imgUrl = ""
		},
		//获取所有品牌数据
		getbrandl() {
			this.$http.post(this.basurl + "classifyList", {
				classifyType: 0
			}).then(res => {
				/* console.log(res) */
				if (res.data.code == 200) {
					this.brandlist = res.data.data
					if(!res.data.data){
						this.$message.error('没有品牌，请去分类添加品牌');
					}
				}else{
					this.$message.error('没有品牌，请去分类添加品牌');
				}
			})
		},
		//获取所有香型数据
		getflavor() {
			this.$http.post(this.basurl + "classifyList", {
				classifyType: 1
			}).then(res => {
				/* console.log(res) */
				if (res.data.code == 200) {
					this.flavorlist = res.data.data
					if(!res.data.data){
						this.$message.error('没有香型，请去分类添加香型');
					}
				}else{
						this.$message.error('没有香型，请去分类添加香型');
					}
			})
		},
		//获取所有度数数据
		getproof() {
			this.$http.post(this.basurl + "classifyList", {
				classifyType: 2
			}).then(res => {
				/* console.log(res) */
				if (res.data.code == 200) {
					this.prooflist = res.data.data
					if(!res.data.data){
						this.$message.error('没有度数，请去分类添加度数');
					}
				}else{
					this.$message.error('没有度数，请去分类添加度数');
					}
			})
		},
		//根据id获取要修改的数据
		getnewlist() {
			this.newwareId = this.$route.query.newwareId
			if (this.$route.query.newwareId) {
				this.$http.post(this.basurl + "ware/wareInfo", {
					wareId: this.newwareId
				}).then(res => {

					if (res.data.code == 200) {
						//console.log('info',res.data.data)
						this.ruleForm = res.data.data[0]
						/* console.log(this.ruleForm) */
						this.flag1 = true
						this.flag2 = false
						this.imgUrl = this.basurl + this.ruleForm.wareCover
						this.coverImg=this.ruleForm.wareCover
						//修改前的数据
						//this.goodsnew = { ...res.data.data[0] }
						//this.imagearurl = this.basurl + this.ruleForm.wareImg
						this.wareImg=res.data.data[0].wareImg
						var wareImg = res.data.data[0].wareImg.split(',')
						for (var i = 0; i < wareImg.length; i++) {
							wareImg[i] = {
								"url":  this.basurl + wareImg[i],
								'name':wareImg[i],
							}
						}
						this.wareImgList = [...wareImg]
						
						this.wareDetails=res.data.data[0].wareDetails
						var wareDetails = res.data.data[0].wareDetails.split(',')
						for (var i = 0; i < wareDetails.length; i++) {
							wareDetails[i] = {
								"url":  this.basurl + wareDetails[i],
								'name':wareDetails[i],
							}
						}
						
						this.wareDetailsList = [...wareDetails]
						//console.log('wareDetailsList',res.data.data[0])
						this.downStatus=res.data.data[0].downStatus
					}
				})
			} else {
				this.flag2 = true
				this.flag1 = false

			}

		}



	},
	mounted() {
		this.getbrandl()
		this.getflavor()
		this.getproof()
		this.getnewlist()

	},

}
</script>
<style lang="less">
.box11 {
	width: 83vw;
	height: 92vh;

	.header_add {
		display: flex;
		justify-content: space-between;
	}

	.add {
		/* margin: 20px 0; */
	}


	.tabfrom {
		.el-form-item {
			margin-bottom: 22px;
			width: 24vw;
			display: inline-block;
		}
		.tuTitle{
			text-align: left;
			display: block;
			font-size: 14px;
			color:#606266;
			padding-left:5px;
		}
		.myImg{
					
			height: 120px;
			overflow-x: hidden;
			.el-form-item {
				width: auto;
			}
			.el-upload--picture-card {
				font-size: 28px;
				color: #8c939d;
				width: 100px;
				height: 100px;
				line-height: 100px;
				text-align: center;
			}
			.el-upload-list--picture-card .el-upload-list__item{
				width: 100px;
				height: 100px;
			}
		}
		.myImg>div{
			min-height: 120px;
			
		}
		.imageaa {
			width: 52vw;

			.avatar-uploader .el-upload {
				border: 1px dashed #d9d9d9;
				border-radius: 6px;
				cursor: pointer;
				position: relative;
				overflow: hidden;
			}

			.avatar-uploader .el-upload:hover {
				border-color: #409EFF;
			}

			.avatar-uploader-icon {
				font-size: 28px;
				color: #8c939d;
				width: 100px;
				height: 100px;
				line-height: 100px;
				text-align: center;
			}

			.avatar {
				width: 100px;
				height: 100px;
				display: block;
			}


		}

		.btnadd {
			display: flex;
			justify-content: center;
			width: 100%;
			margin-top: 30px;

			.el-form-item__content {
				margin-left: 0 !important;

			}
		}

	}
}
</style>